<div class="layui-fluid">
  <div class="layui-row">
    <div class="layui-col-xs12">
      <div class="layui-card">
        <div class="layui-card-header">
          <a href="#/user/index" title="返回"><i class="layui-icon">&#xe65c;</i></a>编辑用户
        </div>
        <div class="layui-card-body">
          <form class="layui-form" action="">
            <div class="layui-form-item">
              <label class="layui-form-label">输入框</label>
              <div class="layui-input-block">
                <div id="test1" class="demo-transfer"></div>
              </div>
            </div>
            <div class="layui-form-item">
              <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="formDemo">立即提交</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>
<script>
  //Demo
  layui.config({
    base: 'js/'
  }).use(['form', 'utils', 'route', 'transfer', 'axios', 'api'], function () {
    var form = layui.form;
    var route = layui.route;
    var utils = layui.utils;
    var transfer = layui.transfer;
    var axios = layui.axios;
    var api = layui.api;
    form.render();

    axios.get(api.role.selectAllRoles, {
      headers: {
        'X-TOKEN': localStorage.getItem('X-TOKEN')
      }
    }).then(resp => {
      var data = resp.data;
      transfer.render({
        id: 'transfer0',
        elem: '#test1',
        title: ['候选角色', '分配角色'],
        data: data,
        parseData: function (res) {
          return {
            "value": res.id,
            "title": res.roleName
          }
        }
      })
    });

    //监听提交
    form.on('submit(formDemo)', function (data) {
      var json = transfer.getData('transfer0');
      var params = route.params();
      var userId = params.id;
      var array = [];
      for (var index in json) {
        array.push(json[index].value);
      }
      var param = {userId: userId, roleIds: array};
      axios.post(api.user.opt, param, {
        headers: {
          'X-TOKEN': localStorage.getItem('X-TOKEN')
        }
      }).then(resp => {
        var data = resp.data;
        if (data.success === true) {
          layer.msg(data.msg);
          location.href = "#/user/list";
        } else {
          layer.alert(data.msg);
        }
      });

      return false;
    });
  });
</script>
<style scoped>

</style>